package com.hb.unic.core.aop;

import java.util.Date;
import java.util.List;

import com.hb.unic.core.base.entity.IBaseEntity;
import com.hb.unic.core.base.enums.IsDeleteEnum;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;



/**
 * 实体类基础属性切面
 *
 * @since v1.0，2023/8/31 19:51，create by Mr.Huang.
 */
@Aspect
@Component
public class BasePropertyAspect {

    /**
     * 新增切面
     */
    @Pointcut("execution(public * com.hb..*.*Mapper.insert*(..)) || execution(public * com.hb..*.*Mapper.save*(..)) || execution(public * com.hb..*.*Mapper.add*(..))")
    public void insertPointCut() {}

    /**
     * 周围通知
     *
     * @param point 调用参数
     * @return Object 方法调用结果
     * @throws Throwable 异常
     */
    @Around("insertPointCut()")
    public Object around(ProceedingJoinPoint point) throws Throwable {
        Object[] args = point.getArgs();
        for (Object arg : args) {
            if (arg instanceof List) {
                List list = (List)arg;
                list.forEach(this::initInsertProperty);
            } else {
                initInsertProperty(arg);
            }
        }
        return point.proceed();
    }

    private void initInsertProperty(Object arg) {
        if (arg instanceof IBaseEntity) {
            IBaseEntity baseEntity = (IBaseEntity)arg;
            baseEntity.setCreateBy("");
            baseEntity.setCreateTime(new Date());
            baseEntity.setUpdateBy("");
            baseEntity.setUpdateTime(new Date());
            baseEntity.setIsDelete(IsDeleteEnum.NOT_DELETE.getValue());
        }
    }

}
